package org.example;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jooby.Jooby;
import io.jooby.MediaType;
import io.jooby.ServerOptions;
import io.jooby.SslOptions;
import io.jooby.avaje.inject.AvajeInjectModule;
import io.jooby.jackson.JacksonModule;
import org.example.config.JacksonSettingSingleton;
import org.example.controller.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Hello world!
 */
public class App extends Jooby {
    private static final Logger log = LoggerFactory.getLogger(App.class);

    {
        //配置avaje inject
        install(AvajeInjectModule.of());
        //配置jackson
        ObjectMapper objectMapper = JacksonSettingSingleton.getObjectMapper();
        install(new JacksonModule(objectMapper));
        //服务器配置
        setServerOptions(new ServerOptions()
                .setBufferSize(16384)
                .setCompressionLevel(6)
                .setPort(8080)
                .setIoThreads(16)
                .setWorkerThreads(64)
                .setDefaultHeaders(true)
                .setMaxRequestSize(10485760)
        );

        // 配置根路径简单的健康检查
        get("/", ctx -> {
            log.debug("根目录/被访问");
            ctx.setResponseType(MediaType.text);
            return "欢迎使用jooby crud程序~~";
        });
        // 配置Controller开始-->|
        mvc(UserController.class);
        // 配置Controller结束|<--
        // 配置简单的异常处理
        error((ctx, cause, statusCode) -> {
            log.error("Error occurred: status={}, path={}", statusCode.value(), ctx.getRequestPath(), cause);
            ctx.setResponseType(MediaType.JSON)
                    .setResponseCode(statusCode)
                    .render("{\"error\": \"" + cause.getMessage() + "\", \"status\": " + statusCode.value() + "}");
        });

        log.info("应用程序启动成功, 监听端口: {}", getServerOptions().getPort());
    }

    public static void main(String[] args) {
        runApp(args, App::new);
    }
}
